﻿
Imports System.DateTime
Imports osi.root.constants

Namespace nowadays
    Public Module _nowadays
        Public Function high_res_ticks() As Int64
            Return _time.high_res_ticks()
        End Function

        Public Function high_res_milliseconds() As Int64
            Return ticks_to_milliseconds(high_res_ticks())
        End Function

        Public Function normal_res_ticks() As Int64
            Return Now().Ticks()
        End Function

        Public Function normal_res_milliseconds() As Int64
            Return ticks_to_milliseconds(normal_res_ticks())
        End Function

        Public Function low_res_ticks() As Int64
            Return milliseconds_to_ticks(low_res_milliseconds())
        End Function

        Public Function low_res_milliseconds() As Int64
            Const revise_interval_ms As UInt32 = 30 * minute_second * second_milli
            Static last_ms As UInt32 = 0
            Static last_revise_ms As UInt32 = 0
            Static offset As Int64 = 0
            Dim lrs As UInt32 = 0
            lrs = last_revise_ms
            Dim c As UInt32 = 0
            c = environment_milliseconds_uint32()
            k_assert(c >= lrs)
            If offset = 0 OrElse
               c < last_ms OrElse
               c - lrs >= revise_interval_ms Then
                For i As Int32 = 0 To 1
                    Dim this As Int64 = 0
                    this = (((Now().milliseconds() - environment_milliseconds_uint32()) -
                             (environment_milliseconds_uint32() - Now().milliseconds())) >> 1)
                    k_assert(this > 0)
                    If i = 0 OrElse
                       this < offset Then
                        offset = this
                    End If
                Next
                c = environment_milliseconds_uint32()
                last_revise_ms = c
            End If
            last_ms = c
            k_assert(offset > 0)
            Return offset + c
        End Function

        Public Function milliseconds() As Int64
            Return low_res_milliseconds()
        End Function

        Public Function ticks() As Int64
            Return low_res_ticks()
        End Function

        Public Function seconds() As Int64
            Return milliseconds_to_seconds(milliseconds())
        End Function
    End Module
End Namespace
